package util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import util.annotation.Check;
import util.annotation.FromTo;
import util.annotation.ValueIn;
import util.annotation.NotNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by chenyipu on 2017/9/7.
 */
@Component
@Aspect
public class AopHandler {
    @Around("@annotation(util.annotation.Check)")
    public Object check(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        long end;
        Object target = joinPoint.getTarget();
        //拦截的方法名
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Method method = null;
        if (!StringUtils.isEmpty(methodName)) {
            Class searchType = target.getClass();
            Method[] methods = searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods();
            int var6 = methods.length;

            for (int var7 = 0; var7 < var6; ++var7) {
                Method methodprim = methods[var7];
                if (methodName.equals(methodprim.getName())) {
                    boolean yes = true;
                    Class<?>[] classs = methodprim.getParameterTypes();
                    if (args.length != classs.length) {
                        continue;
                    }
                    method = methodprim;
                    break;
                }
            }
        }
        Check check = method.getAnnotation(Check.class);
//        if(check)
        Annotation[][] parameterAnnotaions = method.getParameterAnnotations();
        for (int i = 0; i < parameterAnnotaions.length; i++) {
            Annotation[] oneParameterAnnotaions = parameterAnnotaions[i];
            Object arg = args[i];

            checkField(arg,null,check.name(),oneParameterAnnotaions);


        }
        Object o;
        o = joinPoint.proceed(args);
        end = System.currentTimeMillis();
        System.out.println("METHOD:" + method.getName() + " RUNS:" + (end - start) + "(ms).");
        return o;
    }


    private void checkWithValueIn(Object object, ValueIn ValueIn, String desc) {
        boolean matched = false;
        for (Object o : ValueIn.ranges()) {
            if (o.equals(object)) {
                matched = true;
                break;
            }
        }
        if (matched == false) {
            throw new IllegalArgumentException(desc+"下"+ValueIn.name()+"的取值不在取值范围中");
        }
    }

    private boolean isBasicType(Object object, Class classs) {
        if (object == null) {
            if (classs == null) {
                return false;
            } else {
                if (classs.equals(String.class) || classs.equals(Integer.class) //Normal Type
                        || classs.equals(Boolean.class) || classs.equals(Double.class) || classs.equals(Character.class)) {
                    return true;
                }
            }
        } else {
            if (object instanceof String || object instanceof Integer //Normal Type
                    || object instanceof Boolean || object instanceof Double || object instanceof Character) {
                return true;
            }
        }
        return false;
    }

    private boolean checkBasicTypes(Object object, Class classs, ValueIn valueIn, String desc) {
        if (isBasicType(object, classs)) {
            checkWithValueIn("" + object, valueIn,desc);
            return true;
        }
        return false;
    }
    private <T>  T tryCast(Object o){

        try{
            return (T)o;
        }
        catch (Exception e){
            return null;
        }

    }
    private boolean checkField(Object o, Class declaringClass,String desc, Annotation[] annotations) throws Exception {
        for(Annotation annotation:annotations){
            if(annotation instanceof  NotNull) {
                NotNull notNull = tryCast(annotation);
                if (notNull != null && o == null) {
                    throw new IllegalArgumentException(desc+"的"+notNull.name() + "不能为空.");
                }
            }
            if(annotation instanceof  ValueIn) {
                ValueIn ValueIn = tryCast(annotation);
                if (ValueIn != null) {
                    checkBasicTypes(o, declaringClass, ValueIn,desc);
                }
            }
            if(annotation instanceof FromTo&&(o instanceof  Integer||o instanceof  Float||o instanceof  Double||o instanceof  Short||o instanceof  Long)){
                FromTo fromTo = tryCast(annotation);
                if(fromTo!=null&&o!=null){
                    double from = fromTo.from();
                    double to = fromTo.to();

                    Double cur = toDouble(o);

                    boolean leftCheck = cur>from||(fromTo.left()&&cur==from);
                    boolean rightCheck = cur<to||(fromTo.right()&&cur==to);
                    if(!leftCheck||!rightCheck){
                        throw new IllegalArgumentException(desc+"的"+fromTo.name() + "取值越界.");
                    }
                }
            }
            //检查该类是不是Check标注的
            checkObjectWithCheck(declaringClass,o,desc);
        }
        return true;
    }

    private Double toDouble(Object o){
        if(o==null)
        {
            return null;
        }
        if(o instanceof Integer){
            Integer i = tryCast(o);
            return (double)i.intValue();
        }
        if(o instanceof Float){
            Float i = tryCast(o);
            return (double)i.floatValue();
        }
        if(o instanceof Double){
            return (Double) o;
        }
        if(o instanceof Long){
            Long i = tryCast(o);
            return (double)i.longValue();
        }
        if(o instanceof Short){
            Short i = tryCast(o);
            return (double)i.shortValue();
        }
        return null;
    }
    /**
     * 对一个有Check注解的类的对象进行递归判断
     * @param o
     * @param classs
     * @return
     * @throws Exception
     */
    private boolean checkObjectWithCheck(Class classs,Object o,String desc) throws Exception {
        if(o==null&&classs==null){
            return true;
        }
        if(o!=null&&classs==null){
            classs = o.getClass();
        }
        Check check = (Check) classs.getAnnotation(Check.class);
        if (check != null) {
            Field[] fields = classs.getDeclaredFields();
            for (Field field : fields) {
                boolean oldAccessible = field.isAccessible();
                field.setAccessible(true);
                Object obj = field.get(o);
                field.setAccessible(oldAccessible);
                //检查自带的注解
                checkField(obj,field.getType(),desc+"里"+check.name(),field.getAnnotations());

            }
        }
        return true;
    }
}
